﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Coravel.Invocable;
using CRM.Extensions;
using CRM.Services.Email;
using Microsoft.Extensions.Logging;
using Z.EntityFramework.Plus;

namespace CRM.Jobs
{
    /// <summary>
    /// 删除1000条邮件发送数据
    /// <para>防止数据表过大</para>
    /// </summary>
    public class Remove1000EmailLog : IInvocable
    {
        private readonly MyDbContext _dbContext;
        private readonly ILogger<Remove1000EmailLog> _logger;
        private static readonly long ApiNameHashCode = MailjetApplicationService.ApiName.GetFixedHashCode();

        public Remove1000EmailLog(MyDbContext dbContext, ILogger<Remove1000EmailLog> logger)
        {
            _dbContext = dbContext;
            _logger = logger;
        }
        
        public async Task Invoke()
        {
            var threeDaysAgo = DateTime.Today.AddDays(-3);
            var num = 1000;
            var result = await _dbContext.ApiInvokedLogs.Where(a => a.ApiNameHashCode == ApiNameHashCode && a.CreatedAt < threeDaysAgo)
                .OrderBy(a => a.Id).Take(num).DeleteAsync(delete => delete.BatchSize = 1000);
            
            _logger.LogInformation("删除{Date}之前的{Num}条邮件发送数据", threeDaysAgo.ToString("yyyy-MM-dd"), result);
        }
    }
}